package com.cyy.map;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;

/**
 * 通过红黑树实现Map 成为 TreeMap
 * JDK 中的 TreeMap 也是通过红黑树进行实现的
 * @author 会玩的洋洋
 * @since 2022-02-27
 * @param <K>
 * @param <V>
 */
public class TreeMap<K, V> implements Map<K, V> {
    private static final boolean RED = false;
    private static final boolean BLACK = true;

    private int size;

    private Node<K, V> root;

    private Comparator<K> comparator;

    private static class Node<K, V> {
        K key;
        V value;
        Node<K, V> parent;
        Node<K, V> left;
        Node<K, V> right;
        boolean color = RED;

        public Node(K key, V value, Node<K, V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

        public Node() {
        }

        public boolean isLeaf() {
            return left == null && right == null;
        }

        public boolean hasTwoChildren() {
            return left != null && right != null;
        }

        public boolean isLeftChild() {
            return parent != null && parent.left == this;
        }

        public boolean isRightChild() {
            return parent != null && parent.right == this;
        }

        public Node<K, V> sibling() {
            if (isLeftChild()) {
                return parent.right;
            } else if (isRightChild()) {
                return parent.left;
            }
            return null;
        }
    }

    public TreeMap() {
        this(null);
    }

    public TreeMap(Comparator<K> comparator) {
        this.comparator = comparator;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        size = 0;
        root = null;
    }

    @Override
    public V put(K key, V value) {
        this.keyNotNullCheck(key);

        if (root == null) {
            root = new Node<>(key, value, null);
            ++size;
            afterPut(root);
            return null;
        }

        Node<K, V> parent = root;
        Node<K, V> node = root;
        int cmp = 0;
        while (node != null) {
            cmp = compare(key, node.key);
            parent = node;
            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {
                node.key = key;
                V oldValue = node.value;
                node.value = value;
                return oldValue;
            }
        }

        Node<K, V> newNode = new Node<K, V>(key, value, parent);
        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        ++size;

        afterPut(newNode);
        return null;
    }

    @Override
    public V get(K key) {
        Node<K, V> node = node(key);
        return node == null ? null : node.value;
    }

    @Override
    public V remove(K key) {
        return remove(node(key));
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        if (root == null) {
            return false;
        }
        Queue<Node<K, V>> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            Node<K, V> node = queue.poll();
            if (Objects.equals(node.value, value)) {
                return true;
            }
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return false;
    }

    @Override
    public void traversal(Visitor<K, V> visitor) {
        if (visitor == null) {
            return;
        }
        traversal(root, visitor);
    }

    private void traversal(Node<K,V> node, Visitor<K, V> visitor) {
        if (node == null || visitor.stop) {
            return;
        }
        traversal(node.left, visitor);
        if (visitor.stop) {
            return;
        }
        visitor.visit(node.key, node.value);
        traversal(node.right, visitor);
    }

    private V remove(Node<K, V> node) {
        if (node == null) {
            return null;
        }
        --size;

        V oldValue = node.value;

        if (node.hasTwoChildren()) {
            Node<K, V> successor = successor(node);
            node.key = successor.key;
            node.value = successor.value;
            node = successor;
        }

        Node<K, V> replaceNode = node.left != null ? node.left : node.right;
        if (replaceNode != null) {
            replaceNode.parent = node.parent;
            if (node.parent == null) {
                root = replaceNode;
            } else if (node.parent.left == node){
                node.parent.left = replaceNode;
            } else {
                node.parent.right = replaceNode;
            }
            afterRemove(replaceNode);
        } else if (node.parent == null) {
            root = null;

            afterRemove(node);
        } else {
            if (node.parent.left == node) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
            afterRemove(node);
        }

        return oldValue;
    }

    private Node<K, V> node(K key) {
        Node<K, V> node = root;
        while (node != null) {
            int cmp = compare(key, node.key);
            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {
                return node;
            }
        }
        return null;
    }

    private int compare(K k1, K k2) {
        // 如果比较器不为 null 则用比较器比较
        if (comparator != null) {
            return this.comparator.compare(k1, k2);
        }
        // 如果比较器不为 null 则让传入的值实现 Comparable 这个接口的 compareTo 这个方法 来定义的比较方法
        return ((Comparable<K>) k1).compareTo(k2);
    }

    private void leftRotate(Node<K, V> grand) {
        if (grand == null) {
            return;
        }
        Node<K, V> parent = grand.right;
        Node<K, V> child = parent.left;
        grand.right = child;
        parent.left = grand;

        afterRotate(grand, parent, child);
    }

    private void rightRotate(Node<K, V> grand) {
        if (grand == null) {
            return;
        }
        Node<K, V> parent = grand.left;
        Node<K, V> child = parent.right;
        grand.left = child;
        parent.right = grand;

        afterRotate(grand, parent, child);
    }

    private void afterRotate(Node<K, V> grand, Node<K, V> parent, Node<K, V> child) {
        parent.parent = grand.parent;
        if (grand.isLeftChild()) {
            grand.parent.left = parent;
        } else if (grand.isRightChild()) {
            grand.parent.right = parent;
        } else {
            root = parent;
        }

        if (child != null) {
            child.parent = grand;
        }
        grand.parent = parent;
    }

    private Node<K, V> color(Node<K, V> node, boolean color) {
        if (node == null) {
            return null;
        }
        node.color = color;
        return node;
    }

    private Node<K, V> red(Node<K, V> node) {
        return color(node, RED);
    }

    private Node<K, V> black(Node<K, V> node) {
        return color(node, BLACK);
    }

    private boolean colorOf(Node<K, V> node) {
        return node == null ? BLACK : node.color;
    }

    private boolean isBlack(Node<K, V> node) {
        return node == null || node.color == BLACK;
    }

    private boolean isRed(Node<K, V> node) {
        return colorOf(node) == RED;
    }

    private void afterPut(Node<K, V> node) {
        if (node == null) {
            return;
        }
        Node<K, V> parent = node.parent;
        if (parent == null) {
            black(node);
            return;
        }

        if (isBlack(parent)) {
            return;
        }

        Node<K, V> uncle = parent.sibling();
        Node<K, V> grand = red(parent.parent);
        if (isRed(uncle)) {
            black(uncle);
            black(parent);
            afterPut(grand);
            return;
        }

        if (parent.isLeftChild()) {
            if (node.isLeftChild()) {
                black(parent);
            } else {
                leftRotate(parent);
                black(node);
            }
            rightRotate(grand);
        } else {
            if (node.isRightChild()) {
                black(parent);
            } else {
                rightRotate(parent);
                black(node);
            }
            leftRotate(grand);
        }
    }

    private void afterRemove(Node<K, V> node) {
       if (isRed(node)) {
           black(node);
           return;
       }
       Node<K, V> parent = node.parent;
       if (parent == null) {
           return;
       }

       boolean left = parent.left == null || node.isLeftChild();
       Node<K, V> sibling = left ? parent.right : parent.left;

       if (left) {
           if (isRed(sibling)) {
               black(sibling);
               red(parent);
               leftRotate(parent);
               sibling = parent.right;
           }

           if (isBlack(sibling.left) && isBlack(sibling.right)) {
               boolean parentBlack = isBlack(parent);
               red(sibling);
               black(parent);
               if (parentBlack) {
                   afterRemove(parent);
               }
           } else {
               if (isBlack(sibling.right)) {
                   rightRotate(sibling);
                   sibling = parent.right;
               }
               color(sibling, colorOf(parent));
               black(parent);
               black(sibling.right);
               leftRotate(parent);
           }
       } else {
           if (isRed(sibling)) {
               black(sibling);
               red(parent);
               rightRotate(parent);
               sibling = parent.left;
           }

           if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentBlack = isBlack(parent);
                red(sibling);
                black(parent);
                if (parentBlack) {
                    afterRemove(parent);
                }
           } else {
               if (isBlack(sibling.left)) {
                   leftRotate(sibling);
                   sibling = parent.left;
               }
               color(sibling, colorOf(parent));
               black(parent);
               black(sibling.left);
               rightRotate(parent);
           }
       }
    }

    private Node<K, V> successor(Node<K, V> node) {
        if (node == null) {
            return null;
        }
        Node<K, V> s = node.right;
        if (s != null) {
            while (s.left != null) {
                s = s.left;
            }
            return s;
        }

        while (node.parent != null && node.parent.right == node ) {
            node = node.parent;
        }
        return node.parent;
    }

    private void keyNotNullCheck(K key) {
        if (key == null) {
            throw new IllegalArgumentException("Key is not be empty!!");
        }
    }

}
